#include "yuvplayer.h"
#include <QPainter>
#include "ffmpegutil.h"
YUVPlayer::YUVPlayer(QWidget *parent) : QWidget(parent)
{

    setAttribute(Qt::WA_StyledBackground);
    setStyleSheet("background:black");

}

YUVPlayer::~YUVPlayer()
{

    if(imageBuffer) {

        delete [] imageBuffer;
    }

    if(state == Playing) {

        killTimer(timer);
    }

    if(inFile) {

        inFile->close();
    }

    if(image) {

        free(image->bits());
        delete image;
        image = nullptr;
    }

}

int YUVPlayer::init(YUVSpec &yuvSpec)
{

    this->yuvSpec = yuvSpec;

    imageSize = av_image_get_buffer_size(yuvSpec.format,yuvSpec.width,yuvSpec.height,1);

    if(imageSize <= 0) {

        qDebug() << "imageSize:" << imageSize << " error";
        return 1;
    }

    imageBuffer = new char[imageSize];

    if(imageBuffer == nullptr) {

        qDebug() << "imageBuffer new fail";
        return 1;
    }

    inFile = new QFile(yuvSpec.filePath);

    if(!inFile->open(QFile::ReadOnly)) {


        qDebug() << "file path:" << yuvSpec.filePath << " open fail";
        delete [] imageBuffer;
        return 1;
    }


    return 0;
}

void YUVPlayer::start()
{

    startTimer(1000.0 / this->yuvSpec.fps);
    state = Playing;
}

void YUVPlayer::timerEvent(QTimerEvent *event)
{

    int readLen = inFile->read(imageBuffer,imageSize);

    if(readLen != imageSize) {


        killTimer(timer);
    }else {

        if(image) {

            free(image->bits());
            delete image;
            image = nullptr;
        }

        // yuv -> rgb24
        RawVideoFrame inVideoFrame;
        inVideoFrame.data = imageBuffer;
        inVideoFrame.format = AV_PIX_FMT_YUV420P;
        inVideoFrame.width = yuvSpec.width;
        inVideoFrame.height = yuvSpec.height;

        RawVideoFrame outVideoFrame;
        outVideoFrame.format = AV_PIX_FMT_RGB24;
        qDebug() << "width:" << this->height() * (yuvSpec.width*1.0 / yuvSpec.height);
//        outVideoFrame.width = this->height() * (yuvSpec.width*1.0 / yuvSpec.height);
        outVideoFrame.width = 228;
        outVideoFrame.height = this->height();

        FFmpegUtil::convertRawVideo(inVideoFrame,outVideoFrame);
        image = new QImage((uchar*)outVideoFrame.data,outVideoFrame.width,outVideoFrame.height,QImage::Format_RGB888);

        update();
    }
}

void YUVPlayer::paintEvent(QPaintEvent *event)
{

    if(!image) {

        return;
    }

   QPainter painter(this);

   QRect rect((this->width() - image->width())>>1,0,image->width(),image->height());

   painter.drawImage(rect,*image);
}


